//
//  WmcCommonlyAddressDBManager.swift
//  YPWatermarkCamera
//
//  Created by 周诗松 on 2022/4/8.
//

import AMapSearchKit
import Foundation
import HandyJSON
import YPBedrock
import YPNetwork

// MARK: - 扩展WmcCommonlyAddressDBManager + WmcDBProtocol

extension WmcCommonlyAddressDBManager: WmcDBProtocol {
    static var tableName: String = "commonly_address"

    static var dataType: [WmcDBManager.DataType] {
        // !!!: uid是高德地图POI的全局唯一ID
        return [
            .primaryKey(),
            .varchar(name: "uid"),
            .varchar(name: "name"),
            .varchar(name: "address"),
            .varchar(name: "province"),
            .varchar(name: "city"),
            .varchar(name: "district"),
            .real(name: "latitude"),
            .real(name: "longitude"),
        ]
    }
}

// MARK: - [WmcCommonlyAddressDBManager]

struct WmcCommonlyAddressDBManager {
    /// 保存常用地址
    /// - Parameters:
    ///   - model: poi
    ///   - resultBlock: 结果
    static func insert(model: AMapPOI,
                       resultBlock: YPBlock.OneParam<Bool>? = nil)
    {
        let dataList: [WmcDBManager.InsertData] = [
            .init(column: Self.dataType[1], value: model.uid ?? ""),
            .init(column: Self.dataType[2], value: model.name ?? ""),
            .init(column: Self.dataType[3], value: model.address ?? ""),
            .init(column: Self.dataType[4], value: model.province ?? ""),
            .init(column: Self.dataType[5], value: model.city ?? ""),
            .init(column: Self.dataType[6], value: model.district ?? ""),
            .init(column: Self.dataType[7], value: model.location.latitude),
            .init(column: Self.dataType[8], value: model.location.longitude),
        ]

        WmcDBManager.shared.insertData(tableName: Self.tableName, insertData: dataList, resultBlock: resultBlock)
    }

    /// 查询常用地址
    /// - Parameter resultBlock: 结果
    static func query(resultBlock: YPBlock.OneParam<[WmcCommonlyAddressModel]>? = nil) {
        WmcDBManager.shared.searchCustomData(tableName: Self.tableName) { list in
            var result: [WmcCommonlyAddressModel] = []
            list.forEach { data in
                if let model = WmcCommonlyAddressModel.deserialize(from: data) {
                    result.append(model)
                }
            }
            resultBlock?(result)
        }
    }

    /// 删除常用地址
    /// - Parameters:
    ///   - model: poi
    ///   - resultBlock: 结果
    static func delete(model: AMapPOI,
                       resultBlock: YPBlock.OneParam<Bool>? = nil)
    {
        guard let uid = model.uid else {
            resultBlock?(false)
            return
        }
        let condition = "where uid = '\(uid)'"
        WmcDBManager.shared.deleteCustomData(tableName: Self.tableName, condition: condition, resultBlock: resultBlock)
    }
}
